# -*- coding: utf-8 -*-
"""
Created on Fri Oct  1 12:37:09 2021

@author: 刘长奇
"""

import pandas as pd
data = pd.read_csv ("dataset_circles.csv")
import numpy as np
import matplotlib.pyplot as plt
#import random
from sklearn.cluster import KMeans
import math

def avg_center (m):
    ct=np.array([[0,0]])
    ct[0,0]=np.mean(m[:,0])
    ct[0,1]=np.mean(m[:,1])
    return ct

x0,x1,y= np.loadtxt("dataset_circles.csv",delimiter=',', usecols=(0,1,2), 
	unpack=True)

num = np.shape (data) [0]

x0 = x0.reshape(-1,1)
x1 =x1.reshape(-1,1)
#样本数据的两个维度

y=y.reshape(-1,1)
#样本数据的类别

x = np.hstack((x0. reshape(-1,1) ,x1. reshape(-1, 1)))
plt.figure()
plt.scatter(x[:,0],x[:,1],c = y)
plt.title('initial data plot')
plt.colorbar
plt.show ()
#画出数据

#计算两点之间距离
def distance (data1,data2):
    dis=(data1[0]-data2[0])**2+(data1[1]-data2[1])**2
    return dis

#计算角度
def tg (data1,data2):
    return math.atan(data2/data1)

#特征变换到极坐标系
zro=np.array([[0,0]])
temp=np.array([[0,0]])
for i in range(num):
    temp[0]=x[i]
    x[i][1]=tg(x[i,0],x[i,1])
    x[i][0]=distance(zro[0],temp[0])
plt.scatter(x[:,0],x[:,1],c = y)
plt.title('with feature change')
plt.show()
k=2
cs=0
t1=[]
t2=[]
for i in range (num):
    if y[i]==1:
        t1.append(x[i])
    else:
        t2.append(x[i])
t1=np.array(t1)
t2=np.array(t2)
ct_initial=np.array([[0,0],[0,0]])
ct_initial[0]=avg_center(t1)
ct_initial[1]=avg_center(t2)
print(ct_initial)
kmeans = KMeans(n_clusters=2).fit(x)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'm']
markers = ['o', 's', 'D', 'v', '^', 'p', '*', 'o']

plt.title('kmeans')
for i, l in enumerate(kmeans.labels_):
	plt.plot(x[i,0], x[i,1], color = colors[l], marker = markers[l])
plt.plot(ct_initial[0][0],ct_initial[0][1],'k*')
plt.plot(ct_initial[1][0],ct_initial[1][1],'c^')
plt.show()